<?php

namespace app\api\controller;
use app\common\controller\Api;
use app\common\model\Area;
use app\common\model\Cart;
use app\common\model\Goodorder;
use app\common\model\Lights;
use app\common\model\Occupants;
use app\common\model\Ordersessions;
use app\common\model\Rooms;
use app\manystore\model\Categories;
use app\manystore\model\ManystoreShop;
use app\manystore\model\Spece;
use think\Cache;
use think\Db;

/**
 * 点单商品
 */
class Products extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\Products();
    }

    public function categorise(){

      $occ=  Occupants::where('id','=',input('occupants_id'))->find();

      $categorise=  Categories::where('status',1)->where('shop_id',$occ['shop_id'])->field('id,name')->select();
        $this->success('请求成功', $categorise);
    }


    public function products_list()
    {
        $where = []; // 初始化查询条件数组
        if(input('name')!=null&&input('name')!=''){
            $where['name']=input('name');
        }
        if(input('type_id')!=null&&input('type_id')!=''){
            $where['category_id']=input('type_id');
        }
        $occ=  Occupants::where('id','=',input('occupants_id'))->find();

        //$Lights= Lights::where('id',input('lights_id'))->find();

        $where['shop_id']=$occ['shop_id'];
        $query = \app\manystore\model\Products::where('status' ,'=',1);
        if (!empty($where)) {
            $query = $query->where($where);
        }
        $list = $query
            ->field('id, name, image,price')
            ->order('weigh desc')
            ->paginate(10);
        $this->success('请求成功', $list);
    }

    public function products_info(){
        $info=\app\manystore\model\Products::where('id',input('id'))->field('id,carousel,video_url,description,price,sales,stock,name,has_specs')->find();
        if($info){
            $imagesArray = explode(',', $info['carousel']);
            $resultArray = [];
            foreach ($imagesArray as $url) {
                $resultArray[] = ['image' => trim($url)]; // 使用 trim 去除多余的空格
            }
            $info['carousel']=$resultArray;
            $info['video_url']=$info['video_url']==""?[]:explode(',', $info['video_url']);
            if($info['has_specs']==1){
              $spec=  Spece::where('product_id',$info['id'])->select();
              $info['spec']=$spec;
            }
        }
        $this->success('请求成功', $info);
    }

    /*
   * 加入购物车
   */

    public function add_cart(){
        if (!$product_id= input('product_id')) {
            $this->error(__('请选择商品'));
        }
        if (!$num= input('num')) {
            $this->error(__('请选择数量'));
        }
        $spec_id=input('spec_id');
        if(input('spec_id')==null||input('spec_id')==""){
           $Spece= Spece::where('product_id',$product_id)->order('price')->find();
           if($Spece){
               $spec_id=$Spece['id'];
           }else{
               $spec_id=null;
           }
        }

        $cartItem = Cart::where('user_id', $this->auth->id)
            ->where('product_id', $product_id)
            ->where('spec_id', $spec_id)
            ->where('type',1)
            ->find();
        if ($cartItem) {
            $cartItem->num += $num;
            $cartItem->save();
        } else {
            Cart::create([
                'user_id'=>$this->auth->id,
                'product_id'=>$product_id,
                'spec_id'=>$spec_id,
                'type'=>1,
                'num'=>input('num'),
                'occupants_id'=>input('occupants_id'),
            ]);
        }

        $this->success('请求成功', []);
    }

    /*
     * 修改购物车数量
     */
    public function save_cart()
    {
        // 获取输入参数
        $cartId = input('id');
        $num = input('num'); // 假设输入的新的数量

        // 查找购物车记录
        $cartItem = Cart::where('id', $cartId)
            ->find();

        // 检查购物车记录是否存在
        if (!$cartItem) {
            $this->error('购物车记录不存在');
        }

        // 更新购物车数量
        $cartItem->num = $num;
        $cartItem->save();

        // 如果数量为0，则删除该记录
        if ($num <= 0) {
            $cartItem->delete();
            $this->success('请求成功', '已删除购物车记录');
        }

        $this->success('请求成功', '购物车数量已更新');
    }

    /*
     * 结算购物车数据
     */

    public function Cart_list(){
        $cartItems = Cart:: field('id,num')->with('product')

            ->where('cart.user_id', $this->auth->id)
            ->where('cart.type', 1)
            ->where('cart.status', 0)
            ->where('cart.occupants_id', input('occupants_id'))
            ->where('product.status', '1')
            ->select();
        $sum=0;
        foreach ($cartItems as $item){
            $item->getRelation('product')->visible(['id','price','image','name']);
            $sum+=($item->num*$item->product->price);
        }
        return json(['code'=>1,'msg'=>'请求成功','data'=>$cartItems,'money'=>round($sum,2)]);

    }

    public function add_good_order(){

        $data = input('post.');
        $cacheKey = 'submit_' . md5(serialize($data));
        // 检查缓存中是否存在该键名
        if (Cache::has($cacheKey)) {
            $this->error(__('您点的太快了'));
        }
        Cache::set($cacheKey, true, 3);


     $occupants=  occupants::where('id','=',input('occupants_id'))->find();
     if($occupants['status']!==0){
         $this->error('当前订单已结束');
     }
        db::startTrans();
        //1是购物车
        if(input('product_id')==null||input('product_id')==''){
            $array=Cart::where('user_id',$this->auth->id)->where('occupants_id',input('occupants_id'))->where('type',1)->select();
            Cart::where('user_id',$this->auth->id)->where('occupants_id',input('occupants_id'))->where('type',1)->delete();
        }else{
            //2是立即结算
            $array[]=['product_id'=>input('product_id'),'spec_id'=>input('spec_id'),'num'=>input('num')];
        }
       $Ordersessions= Ordersessions::create([
           'occupants_id'=>$occupants['id'],
           'shop_id'=>$occupants['shop_id'],
           'user_id'=>$this->auth->id,
           ]);

        foreach ($array as $item){
            $Products=\app\common\model\Products::where('id',$item['product_id'])->find();
            //多规格
            $has_specs=0;
            $Spece='';
            if($item['spec_id']!=null&&$item['spec_id']!=''){
               $Spece= Spece::where('id',$item['spec_id'])->find();
               $has_specs=1;
            }
            $price=$Spece?$Spece['price']:$Products['price'];
            Goodorder::create([
                'occupants_id'=>$occupants['id'],
                'order_session_id'=>$Ordersessions->id,
                'goodimage'=>$Products['image'],
                'goodname'=>$Products['name'],
                'price'=>$price,
                'goodid'=>$item['product_id'],
                'spec'=>$has_specs==1?$Spece['spec_name']:'常规',
                'num'=>$item['num'],
                'total'=>$item['num']*$price
            ]);
            if($has_specs==0){
               $result= \app\common\model\Products::where('id',$item['product_id'])->where('stock','=',$Products['stock'])->where('stock','egt',$item['num'])->setDec('stock',$item['num']);
            }else{
              $result=  Spece::where('id',$item['spec_id'])->where('stock','=',$Spece['stock'])->where('stock','egt',$item['num'])->setDec('stock',$item['num']);
            }
            if($result==0){
                db::rollback();
                $this->error('商品库存不足');

            }
            Cart::where('id',$item['spec_id'])->delete();
        }
        db::commit();

        $room=Rooms::where('id',$occupants['room_id'])->find();

        $notice=new Notice();
        $notice->Notice($occupants['room_id'],$occupants['shop_id'],$occupants['id'],$room['room_number']. "房间购买商品",$occupants['shop_id']);

        $this->success('请求成功', []);
    }


    //判断有没有进行中的订单
    public function occupants_id(){
        $is_in=Occupants::where('user_id',$this->auth->id)->where('status',0)->find();
        if($is_in==null){
            $this->success('请求成功', ['id'=>0]);
        }else{
            $this->success('请求成功', ['id'=>$is_in['id']]);
        }


    }




}
